import importlib
import sys
from socket import *
from struct import *
from balala import *

importlib.reload(sys)

HOST = '192.168.0.202'  # 本机ip
PORT = 8234   # 监听端口号
BUFSIZ = 4096
ADDR = (HOST, PORT)
SIZE = 10
command = [0x68, 0x00, 0xFE, 0x01, 0x00, 0x00, 0x97, 0x16]  # 数据迁移的命令
reply = [0x68, 0x00, 0xFE, 0x03, 0x00, 0x01, 0x00, 0x94, 0x16]  # 接收回应的命令
datasum = b''


if __name__ == '__main__':
    tcpCliSock = socket(AF_INET, SOCK_STREAM)
    tcpCliSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    tcpCliSock.bind(ADDR)  # 绑定地址端口
    tcpCliSock.listen(SIZE)  # 监听
    conn, addr = tcpCliSock.accept()
    print(addr, "已连接上")
    command_hex = bytearray(command)  # 字节数组发送指令
    conn.send(command_hex)
    while True:
        datarecv = conn.recv(1024)  # 接收数据
        datasum = datasum + datarecv  # 拼接数据包（下位机一次只能发400字节所以需要拼接）
        datasum_memory = memoryview(datasum)  # 接收数据的内存操作
        last = datasum_memory[558:559].tobytes()  # 结束符检测
        head = datasum_memory[0:1].tobytes()  # 开始符检测
        if head != b'\x68':
            input('数据传输失败，请勿断电并再次使用该软件\n按回车关闭')  # 传输的数据长度不对
            break
        if last == b'\x16':
            answer = datasum_memory[6:7].tobytes()  # 下位机回应
            end_flag = datasum_memory[7:8].tobytes()  # 结束标志
            surplus = datasum_memory[8:10].tobytes()  # 剩余人数
            personnelgh = datasum_memory[8:14].tobytes()  # 用户编号
            icnumber = datasum_memory[14:18].tobytes()  # IC卡号
            fv_model = datasum_memory[18:19].tobytes()  # 指静脉模式
            fv_data = datasum_memory[19:555].tobytes()  # 指静脉信息
            PG = unpack('6B', personnelgh)  # 解码
            ICN = unpack('4B', icnumber)  # 解码
            FM = unpack('B', fv_model)  # 解码
            FD = unpack('536B', fv_data)  # 解码
            PG_l = Tuple_B(PG)  # 10进制元组转16进制字符串
            ICN_l = Trans_endian(ICN)  # 10进制元组转16进制字符串并改变大小端
            FM_l = Tuple_A(FM)
            FD_l = Tuple_A(FD)
            sql1 = '''INSERT INTO bus_personnel (personnelcode,icnumber,flagzjm) VALUES (%s,%s,%s);'''  # sql语句插入信息
            data1 = (PG_l, ICN_l, FM_l)
            result1 = writeDb(sql1, data1)
            sql2 = '''INSERT INTO `bus_fingervein` (fingervein,personnelid) VALUES (%s,%s);'''
            data2 = (FD_l, result1[1])  # result[1]即为返回的最后一条数据的id
            result2 = writeDb1(sql2, data2)
            if fv_model == b'\x01':
                writeDb1(sql2, ('00', result1[1]))  # 单指模式填充数据
            if end_flag == b'\x01':
                input('数据传输成功\n按回车关闭')
                break
            elif end_flag == b'\x00':
                datasum = b''
                conn.send(bytearray(reply))
    tcpCliSock.close()
Delete_sql()  # 删除由指静脉双指模式导致的重复数据
